HTMLify
85. Maximal Rectangle.java
Views: 1 | Author: cody
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | // 85. Maximal Rectangle leetcode hard java solution class Solution { public int maximalRectangle(char[][] matrix) { int n = matrix.length; int m = matrix[0].length; int[] arr = new int[m]; int maxi = Integer.MIN_VALUE; for(int i=0; i<n; i++){ for(int j=0; j<m; j++){ if(i==0){ arr[j]= matrix[i][j]-'0'; }else { if(matrix[i][j]=='1'){ arr[j] += matrix[i][j]-'0'; }else{ arr[j]=0; } } } maxi = Math.max(maxi,largestRectangleArea(arr)); } return maxi; } public int largestRectangleArea(int[] heights) { Stack<Integer> s = new Stack<>(); int ans = 0; for(int i = 0; i<=heights.length; i++){ int temp = 0; if(i != heights.length) temp = heights[i]; while(s.size()>0 && temp < heights[s.peek()]){ int tbs = s.pop(); int nsr = i; int x1 = nsr-1; int nsl = -1; if(s.size() != 0) nsl = s.peek(); int x2 = nsl+1; int area = heights[tbs] * (x1 -x2 +1); ans = Math.max(ans,area); } s.push(i); } return ans; } } |